package map;

import java.util.Comparator;
import java.util.TreeMap;

/**
 * Created with IntelliJ IDEA
 * Description:TreeMap学习
 * User:22954
 * Date:2024-02-21
 * Time:2:01
 */
@SuppressWarnings("all")
public class TreeMap_ {
    /*
    1.TreeMap继承AbstractMap实现Map接口
    2.TreeMap底层是红黑树
    3.TreeMap储存的<K,V>键值对,key不能为null,value可以为null,
    4.treeMap会对传入的key按默认或设定的比较器判断是否存在并将<K,V>排序
      当程序判断key值已存在时,仅将newValue替换oldValue,key不会变化
    5.当调用无参构造器时,key对象必须实现Comparable接口
     */
    public static void main(String[] args) {
        TreeMap<String, Integer> treeMap = new TreeMap<>(new Comparator<String>() {
            @Override
            public int compare(String o1, String o2) {
                return o1.length() - o2.length();
            }
        });
        treeMap.put("zhangsan", 15);
        treeMap.put("lisi", 62);
        treeMap.put("wangwu", 842);
        treeMap.put("zhaoer", 34);
        System.out.println(treeMap);//{lisi=62, wangwu=34, zhangsan=15}
    }

    public static void main1(String[] args) {
        TreeMap<String, Integer> treeMap = new TreeMap<>();
        treeMap.put("zhangsan", 15);
        treeMap.put("lisi", 62);
        treeMap.put("wangwu", 842);
        treeMap.put("zhaoer", 34);
        System.out.println(treeMap);//{lisi=62, wangwu=842, zhangsan=15, zhaoer=34}
        treeMap.put("lisi", 00);
        System.out.println(treeMap);//{lisi=0, wangwu=842, zhangsan=15, zhaoer=34}
    }
}
